/**
 * Created by abel.lin on 2017/8/14.
 */

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author abel.lin
 * @date_time 2017/8/14 17:59
 * @description
 */
public class LotteryUtil {
    public static LotteryAwards lottery(List<LotteryAwards> awardList) {
        if (awardList == null || awardList.isEmpty()) {
            return null;
        }

        int size = awardList.size();

        // 计算总概率，这样可以保证不一定总概率是1
        double sumRate = 0d;
        for (LotteryAwards rate : awardList) {
            sumRate += rate.getWeight();
        }

        // 计算每个物品在总概率的基础下的概率情况
        List<Double> sortOrignalRates = new ArrayList<Double>(size);
        Double tempSumRate = 0d;
        for (LotteryAwards rate : awardList) {
            tempSumRate += rate.getWeight();
            sortOrignalRates.add(tempSumRate / sumRate);
        }

        // 根据区块值来获取抽取到的物品索引
        double nextDouble = Math.random();
        sortOrignalRates.add(nextDouble);
        Collections.sort(sortOrignalRates);
        int index = sortOrignalRates.indexOf(nextDouble);

        return awardList.get(index);
    }
}
